package com.scalar.chiptrack.adaptor.ikanos.stats;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.ScalarException;
import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.NVPair;
import HTTPClient.CookieModule;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Calendar;

/**
 * User: ChandraSekhar
 * Date: Jul 3, 2008
 * Time: 5:38:54 PM
 */
public class STATSAdaptor extends JobHandler implements AdaptorConstants
{
    private static final String PROTOCOL_SCHEME_HTTPS = "https";
    private static String HOST = "my.statschippac.com";
    private static final int DEFAULT_SSL_PORT = 443;

    public static String FILE_NAME_WIP_INVENTORY    = "WIP_Inventory_Report";
    public static String FILE_NAME_DROP_SHIP        = "DropShip_Report";
    public static String FILE_NAME_SCS_TRANSACTION  = "SCS_Transaction_Report";
    public static String FILE_NAME_TRANSACTION      = "SCKSCCSCM_Transaction_Report";
    public static String FILE_NAME_SHIP_ALERT       = "Shipping_Report";

    public static final String ADAPTOR_NAME = "STATS_WIP";

    private int wipIterations = 0;
    private int dropshipIterations = 0;
    private int transReportIterations = 0;
    private int transSCSReportIterations = 0;
    private int shipReportIterations = 0;

    private Logger m_adaptorLogger = null;
    private String m_dataOutputDir = null;

    private String m_username = null;
    private String m_password = null ;
    private int    m_adaptor_id     = -1;

    public STATSAdaptor() throws ScalarException
    {
        try
        {
        	wipIterations = 0; // If CSV file could not be retrived with the first response system will try for another three times.
        	dropshipIterations = 0;
            transReportIterations = 0;
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation( VENDOR_NAME_SCS, LOCATION_TYPE_ASSEMBLY);

            m_username = vendorAdaptor.getUserId().trim();
            m_password = vendorAdaptor.getPassWord().trim();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory().trim();

            if ( m_dataOutputDir != null )
            {
                if ( m_dataOutputDir.endsWith( "/" ) || m_dataOutputDir.endsWith( "\\" ) )
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }

                AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
                m_adaptorLogger  =  AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_SCS );
                AdaptorUtils.setLogger( m_adaptorLogger );
            }
        }
        catch ( ScalarException se )
        {
            log( "ERROR!! ERROR!! ERROR!! Exception while loading STATS Adaptor Username, Password details from database, Exception: " + se );
            throw se;
        }
    }

    public static void main( String[] args )  throws Exception
    {

        try
        {
            new STATSAdaptor().execute();
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
    }

    public void execute() throws Exception
    {
        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);
            //Print the header details
            AdaptorUtils.printHeader( "STATS ChipPac", CONSTANT_ADAPTOR);

            AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger );

            //login to the Site

           login( HOST, DEFAULT_SSL_PORT);

        }
        catch (Exception e )
        {
            String stackTrace = e.toString();
            if ( stackTrace.indexOf("Could not create response object") > -1 )
            {
                System.out.println("## Unable to download some files ##");
            }
            else
            {
                AdaptorUtils.removeOldFiles( m_dataOutputDir, m_adaptorLogger);
                AdaptorRunInfo.updatedAdaptorStatus( CONSTANT_FAILURE, m_adaptor_id );
                System.out.println("Exception while trying to connect and read data from "+HOST +" site: " + e);
                e.printStackTrace();
                throw e;
            }
        }
    }

    private void login( String host, int port) throws Exception
    {

        HTTPConnection conn = null;

        conn = new HTTPConnection( PROTOCOL_SCHEME_HTTPS, host, port );

        NVPair defaultHeaders[] = new NVPair[6];
        defaultHeaders[0] = new NVPair( "Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, **/*//*" );
        defaultHeaders[1] = new NVPair( "Referer", "https://" + host );
        defaultHeaders[2] = new NVPair( "Accept-Language", "hi" );
        defaultHeaders[3] = new NVPair( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" );
        defaultHeaders[4] = new NVPair( "Host", host );
        defaultHeaders[5] = new NVPair( "Proxy-Connection", "Keep-Alive" );

        // Accept all cookies
        CookieModule.setCookiePolicyHandler( null );
        HTTPConnection.addDefaultModule( CookieModule.class, -1 );
        //conn.setDefaultHeaders( defaultHeaders );

        System.out.print( "Trying to login...." );
        log( "\nTrying to log in... " );

        HTTPResponse rsp = conn.Get( "/portal/page?_pageid=44,34036&_dad=portal&_schema=PORTAL" );

        readData( rsp, 1 );
        HTTPConnection conn1 = null;
        //https://mylogin.statschippac.com/pls/orasso/orasso.wwsso_app_admin.fapp_process_login?p_app_id=90F95C7968502B4D0000000000000116
        conn1 = new HTTPConnection( PROTOCOL_SCHEME_HTTPS, "mylogin.statschippac.com", port );
        HTTPConnection.addDefaultModule( CookieModule.class, -1 );

        NVPair[] formData = new NVPair[4];

        formData[0] = new NVPair( "password", m_password );
        formData[1] = new NVPair( "p_request", "" );
        formData[2] = new NVPair( "ssousername", m_username );
        formData[3] = new NVPair( "site2pstoretoken", "v1.2~98C84119~ACC81D2CBD680491182A4F3AB0FF4D3F33C9BE080DB6C26314D6D98F7626E62E4A9C4E6359205032A6E1D5E4674BE8A639CE8BD5381839A9E2518644731E8AB4A98B4D22080A482D138E87EA2087EBD4F7FB31BE30B108909AC0445AD5D0E713FB981FA6679A25C0EF8599D5172AAB419A4094A6F7150BEEFA319D85AEBF2D20FE4B7C3BDC39AB4D8537421AC63F98618D9C8FD1345E26B6593996E06B43B0C88A364475069EE05139FC050109BE128DC9A702F1ED10FB518D4D4862C63BFE1532BB4486CD81291627AF647659D73F59" );

        HTTPResponse rsp1 = conn1.Post( "/pls/orasso/orasso.wwsso_app_admin.ls_login",  formData );

        readData( rsp1, 1 );
        //rsp1 = conn.Get( "/portal/page?_pageid=44,34150,44_35217&_dad=portal&_schema=PORTAL" );
        rsp1 = conn.Get( "/portal/page?_pageid=44,34150,44_35341&_dad=portal&_schema=PORTAL" );

        //For Downloading the Raw Data of WipInventory Search Query (for All Plants)
        requestWipInventorySearchAllPlants( conn, conn1);

        //For Downloading the Drop Ship Inventory Search Query (for All Plants)
        requestDropShipInventoryAllPlants( conn, conn1);

        //For Downloading the Tranaction Report (for SCS Plants)
        requestSCSTransactionReport( conn, conn1);

        //For Downloading the Tranaction Report (for All Plants)
        requestTransactionReport( conn, conn1);

        //For Downloading the ShipAlert Report (for All Plants)
        //requestShipAlertReport( conn, conn1);

        //For Downloading the Standard Report(Internet File System)
        //requestStandardReportsIFS( conn, conn1);

        System.out.println( "done." );
        log( "done" );
        //return conn1;
    }
  
    /**
     *
     * @param conn
     * @param conn1
     * @return
     * @throws Exception
     */
    private void requestWipInventorySearchAllPlants( HTTPConnection conn, HTTPConnection conn1 ) throws Exception
    {
        HTTPResponse rsp = null;
        BufferedReader reader = null;

        try
        {     //https://my.statschippac.com/discoverer/viewer?us=ikns_becky&pw=st853515&db=odsprod&wb=ODSU3RPT.006.0%20WIP%20and%20Inventory%20Search%20Query&nlsl=en-us
            System.out.println( "\nSubmitting request for Wip Inventory for all Plants..." );
            log( "\nSubmitting request for Wip Inventory for all parts..." );

            //rsp = conn1.Get( "/pls/orasso/orasso.wwsso_app_admin.fapp_process_login?p_app_id=90F95C7968502B4D0000000000000116" );
            //rsp = conn.Get( "/discoverer/viewer?us=ikns_becky&pw=st853515&db=odsprod&wb=ODSU3RPT.006.0%20WIP%20and%20Inventory%20Search%20Query&nlsl=en-us" );

            //rsp = conn.Get( "/discoverer/viewer?&cn=tm4i_connection1&us=%7E27IKNS_BECKY%7E27&db=odsprod&lm=discoverer&eul=ODS_EUL&nlsl=en-us&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227");

            //rsp = conn.Get("/discoverer/viewer?_lfs=true&cn=tm4i_connection1&pw=st853515&db=odsprod&eul=ODS_EUL&formSubmitted.x=27&formSubmitted.y=13&lm=discoverer&nlsl=en-us&pg=1&us=IKNS_BECKY&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227");


            //rsp = conn.Get( "/discoverer/viewer?&cn=tm4i_connection1&us=%7E27IKNS_BECKY%7E27&db=odsprod&lm=discoverer&eul=ODS_EUL&nlsl=en-us&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227&pg=1&_act=seo");

            
            //readData( rsp,0 );
            //rsp = conn.Post( "/discoverer/viewer?&cn=tm4i_connection1&us=~27IKNS_BECKY~27&db=odsprod&lm=discoverer&eul=ODS_EUL&nlsl=en-us&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227&pg=1&wqcn=true&fm=xls");
            
            rsp = conn.Get("/discoverer/viewer?&_lfs=true&cn=tm4i_connection1&pw=st853515&db=odsprod&eul=ODS_EUL&fm=csv&lm=discoverer&nlsl=en-us&pg=1&us=~27IKNS_BECKY~27&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227&wqcn=true");

            //readData( rsp1,0 );

            if ( rsp != null )
            {
                if( rsp.getHeader("Content-Type").equalsIgnoreCase( "application/csv; charset=UTF-8" ) )
            	{
	                reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
	                if ( reader != null )
	                {
	                    System.out.println( "\tDownloading and saving the Wip Inventory Report for all Plants..." );
	                    log( "\tDownloading and saving the Wip Inventory Report for all Plants..." );
	                    AdaptorUtils.saveAsFile( reader , m_dataOutputDir, FILE_NAME_WIP_INVENTORY, FILE_EXTN_CSV);
	                    if ( m_adaptor_id > 0 )
	                    {
	                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_WIP_INVENTORY, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
	                    }
	                }
	                else
	                {
	                    log( "Could not save Wip Inventory Report for all Plants from Buffer Reader" );
	                    throw new ScalarException( "Could not save Wip Inventory Report for all Plants from Buffer Reader" );
	                }
	            }
	            else
	            {
	            	log( "Could not create response object of Wip Inventory Report for all Plants" );
	            	System.out.println("Could not retreive the Wip Information so trying again");
                    //log("wipIterations = " + wipIterations);
                    if( wipIterations < 5 )
	            	{
	            		wipIterations++;
	            		requestWipInventorySearchAllPlants( conn, conn1 );
	            	}
	            	else
	            	{
	            		throw new ScalarException( "Could not create response object of Wip Inventory Report for all Plants" );
	            	}
	            }
            }
            else
            {
                log( "Could not create response object of Wip Inventory Report for all Plants" );
                throw new ScalarException( "Could not create response object of Wip Inventory Report for all Plants" );
            }
        }
        finally
        {
             if ( reader != null )
             {
                 reader.close();
             }
        }
    }

    private void requestDropShipInventoryAllPlants( HTTPConnection conn, HTTPConnection conn1 ) throws Exception
    {
        HTTPResponse rsp = null;
        BufferedReader reader = null;

        try
        {
            System.out.println( "\nSubmitting request for Drop Ship Inventory for all Plants..." );
            log( "\nSubmitting request for Drop Ship Inventory for all parts..." );

            //rsp = conn1.Get( "/pls/orasso/orasso.wwsso_app_admin.fapp_process_login?p_app_id=90F95C7968502B4D0000000000000109" );

            //rsp = conn.Get( "/discoverer/viewer?us=ikns_becky&pw=st853515&db=odsprod&wb=ODSU3RPT.003.0%20Dropship%20Inventory%20Report%20Query&nlsl=en-us" );
            //readData( rsp,0 );
            //rsp = conn.Get( "/discoverer/viewer?&cn=tm4i_connection1&us=%7E27IKNS_BECKY%7E27&db=odsprod&lm=discoverer&eul=ODS_EUL&nlsl=en-us&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227");

            //rsp = conn.Get("/discoverer/viewer?_lfs=true&cn=tm4i_connection1&pw=st853515&db=odsprod&eul=ODS_EUL&formSubmitted.x=27&formSubmitted.y=13&lm=discoverer&nlsl=en-us&pg=1&us=IKNS_BECKY&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227");


            //rsp = conn.Get( "/discoverer/viewer?&cn=tm4i_connection1&us=%7E27IKNS_BECKY%7E27&db=odsprod&lm=discoverer&eul=ODS_EUL&nlsl=en-us&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227&pg=1&_act=seo");

            //readData( rsp,0 );
            //rsp = conn.Post( "/discoverer/viewer?&cn=tm4i_connection1&us=~27IKNS_BECKY~27&db=odsprod&lm=discoverer&eul=ODS_EUL&nlsl=en-us&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227&pg=1&wqcn=true&fm=xls");

            rsp = conn.Get("/discoverer/viewer?&_lfs=true&cn=tm4i_connection1&pw=st853515&db=odsprod&eul=ODS_EUL&fm=csv&lm=discoverer&nlsl=en-us&pg=1&qp_Plant1=SCM~2cSCC~2cSCK~2cSCS&us=~27IKNS_BECKY~27&wbk=0030_DROPSHIP_INVENTORY_REPORT_QUERY31161&wsk=5268&wqcn=true");

            //readData( rsp1,0 );

            if ( rsp != null )
            {
            	if( rsp.getHeader("Content-Type").equalsIgnoreCase( "application/csv; charset=UTF-8" ) )
            	{
	                reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
	                if ( reader != null )
	                {
	                    System.out.println( "\tDownloading and saving the Drop Ship Inventory Report for all Plants..." );
	                    log( "\tDownloading and saving the Drop Ship Inventory Report for all Plants..." );
	                    AdaptorUtils.saveAsFile( reader , m_dataOutputDir, FILE_NAME_DROP_SHIP, FILE_EXTN_CSV);
	                    if ( m_adaptor_id > 0 )
	                    {
	                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_DROP_SHIP, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
	                    }
	                }
	                else
	                {
	                    log( "Could not save Drop Ship Inventory Report for all Plants from Buffer Reader" );
	                    throw new ScalarException( "Could not save Drop Ship Inventory Report for all Plants from Buffer Reader" );
	                }
            	}
	            else
	            {
	            	log( "Could not create response object of Drop Ship Inventory Report for all Plants" );
	            	System.out.println("Could not retreive the Drop Ship Information so trying again");
	            	if( dropshipIterations < 5 )
	            	{
	            		dropshipIterations++;
	            		requestDropShipInventoryAllPlants( conn, conn1 );
	            	}
	            	else
	            	{
	            		throw new ScalarException( "Could not create response object of Drop Ship Inventory Report for all Plants" );
	            	}
	            }
            }
            else
            {
                log( "Could not create response object of Drop Ship Inventory Report for all Plants" );
                throw new ScalarException( "Could not create response object of Drop Ship Inventory Report for all Plants" );
            }
        }
        finally
        {
             if ( reader != null )
             {
                 reader.close();
             }
        }
    }

    private synchronized void requestSCSTransactionReport( HTTPConnection conn, HTTPConnection conn1 ) throws Exception
    {
        HTTPResponse rsp = null;
        BufferedReader reader = null;

        try
        {
            String endDate     = DateUtil.getCurrentDate( "dd-MMM-yyyy" ).toUpperCase();
            String beginDate  =  DateUtil.getPreviousDate(7, "dd-MMM-yyyy" ).toUpperCase();

            //System.out.println("endDate = " + endDate.toUpperCase() );
            //System.out.println("beginDate = " + beginDate.toUpperCase() );
            
            //rsp = conn1.Get("/pls/orasso/orasso.wwsso_app_admin.fapp_process_login?p_app_id=90F95C7968502B4D0000000000000120");

            //rsp = conn.Get("/discoverer/viewer?&amp;cn=tm4i_connection1&amp;us=%7E27IKNS_BECKY%7E27&amp;db=odsprod&amp;lm=discoverer&amp;eul=ODS_EUL&amp;nlsl=en-us&amp;wbk=0200_MAIN_PROCESS_TRANSACTION_REPORT_BETA_VERSION1141&amp;wsk=2739");
            //readData( rsp,0 );
            System.out.println( "\nSubmitting request for Tranaction Report for SCS Plant..." );
            log( "\nSubmitting request for Tranaction Report for SCS Plant..." );

            ///discoverer/viewer?&_lfs=true&cn=tm4i_connection1&pw=st853515&db=odsprod&eul=ODS_EUL&fm=csv&lm=discoverer&nlsl=en-us&pg=1&qp_End~20Date=28-NOV-2008~2023~3a59~3a59&qp_Start~20Date=19-NOV-2008~2000~3a00~3a00&us=~27IKNS_BECKY~27&wbk=0200_MAIN_PROCESS_TRANSACTION_REPORT_BETA_VERSION1141&wqcn=true&wsk=2739");

            ///discoverer/viewer?cn=tm4i_connection1&db=odsprod&eul=ODS_EUL&lm=discoverer&nlsl=en-us&pg=1&qp_End~20Date=28-OCT-09~2023~3a59~3a59&qp_Start~20Date=20-COT-09~2000~3a00~3a00&us=~27IKNS_BECKY~27&wbk=0201_MES_MAIN_PROCESS_TRANSACTION_REPORT11&wsk=4781

            //**************COMENTED LINK IS FOR ONLY SCS PLANT**********
            rsp = conn.Get("/discoverer/viewer?cn=tm4i_connection1&db=odsprod&eul=ODS_EUL&lm=discoverer&nlsl=en-us&fm=csv&pg=1&qp_End~20Date="+endDate+"~2023~3a59~3a59&qp_Start~20Date="+beginDate+"~2000~3a00~3a00&us=~27IKNS_BECKY~27&pw=st853515&wbk=0200_MAIN_PROCESS_TRANSACTION_REPORT_BETA_VERSION1141&wsk=2739");

            //log("rsp.getEffectiveURI() = " + rsp.getEffectiveURI());
            //readData( rsp,0 );

            synchronized( this )
            {
                wait(100000);
            }
            this.notify();

            rsp = conn.Get("/discoverer/viewer?cn=tm4i_connection1&db=odsprod&eul=ODS_EUL&lm=discoverer&nlsl=en-us&fm=csv&pg=1&qp_End~20Date="+endDate+"~2023~3a59~3a59&qp_Start~20Date="+beginDate+"~2000~3a00~3a00&us=~27IKNS_BECKY~27&pw=st853515&wbk=0200_MAIN_PROCESS_TRANSACTION_REPORT_BETA_VERSION1141&wsk=2739");

            if ( rsp != null )
            {
                //System.out.println("rsp.getHeader() = " + rsp.getHeader("Content-Type"));
                if( rsp.getHeader("Content-Type").equalsIgnoreCase( "application/csv; charset=UTF-8" ) )
                {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\tDownloading and saving the Transaction Report for SCS Plant..." );
                        log( "\tDownloading and saving the Transaction Report for SCS Plant..." );
                        AdaptorUtils.saveAsFile( reader , m_dataOutputDir, FILE_NAME_SCS_TRANSACTION, FILE_EXTN_CSV);
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_SCS_TRANSACTION, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Tranaction Report for SCS Plant from Buffer Reader" );
                        throw new ScalarException( "Could not save Tranaction Report for SCS Plant from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Tranaction Report for SCS Plant" );
                    System.out.println("Could not retreive the Tranaction Report for SCS Plant, so trying again");
                    if( transSCSReportIterations < 3 )
                    {
                        transSCSReportIterations++;
                        requestSCSTransactionReport( conn, conn1 );
                    }
                    else
                    {
                        throw new ScalarException( "Could not create response object of Tranaction Report for SCS Plant" );
                    }
                }
            }
            else
            {
                log( "Could not create response object of Tranaction Report for SCS Plant" );
                throw new ScalarException( "Could not create response object of Tranaction Report for SCS Plant" );
            }
        }
        finally
        {
             if ( reader != null )
             {
                 reader.close();
             }
        }
    }

    private synchronized void requestTransactionReport( HTTPConnection conn, HTTPConnection conn1 ) throws Exception
    {
        HTTPResponse rsp = null;
        BufferedReader reader = null;

        try
        {
            String endDate     = DateUtil.getCurrentDate( "dd-MMM-yyyy" ).toUpperCase();
            String beginDate  =  DateUtil.getPreviousDate(7, "dd-MMM-yyyy" ).toUpperCase();


            System.out.println( "\nSubmitting request for Tranaction Report for SCK,SCC,SCM Plants..." );
            log( "\nSubmitting request for Tranaction Report for SCK,SCC,SCM Plants..." );

            rsp = conn.Get("/discoverer/viewer?cn=tm4i_connection1&db=odsprod&eul=ODS_EUL&lm=discoverer&nlsl=en-us&fm=csv&pg=1&qp_End~20Date="+endDate+"~2023~3a59~3a59&qp_Start~20Date="+beginDate+"~2000~3a00~3a00&us=~27IKNS_BECKY~27&pw=st853515&wbk=0201_MES_MAIN_PROCESS_TRANSACTION_REPORT11&wsk=4781");

            //log("rsp.getEffectiveURI() = " + rsp.getEffectiveURI());
            //readData( rsp,0 );

            synchronized( this )
            {
                wait(100000);
            }
            this.notify();

            rsp = conn.Get("/discoverer/viewer?cn=tm4i_connection1&db=odsprod&eul=ODS_EUL&lm=discoverer&nlsl=en-us&fm=csv&pg=1&qp_End~20Date="+endDate+"~2023~3a59~3a59&qp_Start~20Date="+beginDate+"~2000~3a00~3a00&us=~27IKNS_BECKY~27&pw=st853515&wbk=0201_MES_MAIN_PROCESS_TRANSACTION_REPORT11&wsk=4781");


            if ( rsp != null )
            {
                //System.out.println("rsp.getHeader() = " + rsp.getHeader("Content-Type"));
                if( rsp.getHeader("Content-Type").equalsIgnoreCase( "application/csv; charset=UTF-8" ) )
                {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\tDownloading and saving the Transaction Report for SCK,SCC,SCM Plant..." );
                        log( "\tDownloading and saving the Transaction Report for SCK,SCC,SCM Plant..." );
                        AdaptorUtils.saveAsFile( reader , m_dataOutputDir, FILE_NAME_TRANSACTION, FILE_EXTN_CSV);
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_TRANSACTION, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Tranaction Report for SCK,SCC,SCM Plant from Buffer Reader" );
                        throw new ScalarException( "Could not save Tranaction Report for SCK,SCC,SCM Plant from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Tranaction Report for SCK,SCC,SCM Plant" );
                    System.out.println("Could not retreive the Tranaction Report for SCK,SCC,SCM Plant, so trying again");
                    if( transReportIterations < 3 )
                    {
                        transReportIterations++;
                        requestTransactionReport( conn, conn1 );
                    }
                    else
                    {
                        throw new ScalarException( "Could not create response object of Tranaction Report for SCK,SCC,SCM Plant" );
                    }
                }
            }
            else
            {
                log( "Could not create response object of Tranaction Report for SCK,SCC,SCM Plant" );
                throw new ScalarException( "Could not create response object of Tranaction Report for SCK,SCC,SCM Plant" );
            }
        }
        finally
        {
             if ( reader != null )
             {
                 reader.close();
             }
        }
    }

    private synchronized void requestShipAlertReport( HTTPConnection conn, HTTPConnection conn1 ) throws Exception
    {
        HTTPResponse rsp = null;
        BufferedReader reader = null;

        try
        {
            Calendar cal = Calendar.getInstance();

            cal.add( Calendar.DAY_OF_MONTH, 1);
            String endDate     = StringUtils.formatDateToString( cal.getTime(), "dd-MMM-yyyy" ).toUpperCase();
            cal.add( Calendar.DAY_OF_MONTH, -30 );
            String beginDate  =  StringUtils.formatDateToString( cal.getTime(), "dd-MMM-yyyy" ).toUpperCase();

            System.out.println( "\nSubmitting request for Ship Alert Report for SCS Plant..." );
            log( "\nSubmitting request for Ship Alert Report for SCS Plant..." );

            //              /discoverer/viewer?cn=tm4i_connection1&db=odsprod&eul=ODS_EUL&lm=discoverer&nlsl=en-us&pg=1&qp_fromdate=27-SEP-09&qp_todate=22-OCT-09&us=~27IKNS_BECKY~27&wbk=ELEMENT141116&wsk=2996
            rsp = conn.Get("/discoverer/viewer?cn=tm4i_connection1&db=odsprod&eul=ODS_EUL&lm=discoverer&nlsl=en-us&fm=csv&pg=1&qp_fromdate="+beginDate+"&qp_todate="+endDate+"&us=~27IKNS_BECKY~27&pw=st853515&wbk=ELEMENT141116&wsk=198");

            /*synchronized( this )
            {
                wait(200000);
            }
            this.notify();*/
            /*rsp = conn.Get("/discoverer/viewer?cn=tm4i_connection1&db=odsprod&eul=ODS_EUL&lm=discoverer&nlsl=en-us&fm=csv&pg=1&qp_fromdate=27-SEP-09&qp_todate=22-OCT-09&us=~27IKNS_BECKY~27&pw=st853515&wbk=ELEMENT141116&wsk=198");*/

            if ( rsp != null )
            {
                //System.out.println("rsp.getHeader() = " + rsp.getHeader("Content-Type"));
                if( rsp.getHeader("Content-Type").equalsIgnoreCase( "application/csv; charset=UTF-8" ) )
                {
                    reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                    if ( reader != null )
                    {
                        System.out.println( "\tDownloading and saving the Ship Alert Report for SCS Plant..." );
                        log( "\tDownloading and saving the Ship Alert Report for SCS Plant..." );
                        AdaptorUtils.saveAsFile( reader , m_dataOutputDir, FILE_NAME_SHIP_ALERT, FILE_EXTN_CSV);
                        if ( m_adaptor_id > 0 )
                        {
                            AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , FILE_NAME_SHIP_ALERT, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                        }
                    }
                    else
                    {
                        log( "Could not save Ship Alert Report for SCS Plant from Buffer Reader" );
                        throw new ScalarException( "Could not save Ship Alert Report for SCS Plant from Buffer Reader" );
                    }
                }
                else
                {
                    log( "Could not create response object of Ship Alert Report for SCS Plant" );
                    System.out.println("Could not retreive the Ship Alert Report for SCS Plant, so trying again");
                    if( shipReportIterations < 5 )
                    {
                        shipReportIterations++;
                        requestShipAlertReport( conn, conn1 );
                    }
                    else
                    {
                        throw new ScalarException( "Could not create response object of Ship Alert Report for SCS Plant" );
                    }
                }
            }
            else
            {
                log( "Could not create response object of Ship Alert Report for SCS Plant" );
                throw new ScalarException( "Could not create response object of Ship Alert Report for SCS Plant" );
            }
        }
        finally
        {
             if ( reader != null )
             {
                 reader.close();
             }
        }
    }

    private void requestStandardReportsIFS( HTTPConnection conn, HTTPConnection conn1 ) throws Exception
    {
        HTTPResponse rsp = null;
        BufferedReader reader = null;

        try
        {
            HTTPConnection conn2 = null;

            conn2 = new HTTPConnection( PROTOCOL_SCHEME_HTTPS, "ifs.statschippac.com", DEFAULT_SSL_PORT );
            CookieModule.setCookiePolicyHandler( null );
            HTTPConnection.addDefaultModule( CookieModule.class, -1 );

            System.out.println( "\nSubmitting request for Standard Reports From IFS..." );
            log( "\nSubmitting request for Standard Reports From IFS..." );

            rsp = conn1.Get( "/pls/orasso/orasso.wwsso_app_admin.fapp_process_login?p_app_id=90F95C7968502B4D0000000000000118" );
            //readData(rsp, 0);
            STATSHtmlParser parser = new STATSHtmlParser();

            parser.parse( new InputStreamReader( rsp.getInputStream() ) );

            System.out.println("parser.getToken() = " + parser.getToken());

            NVPair[] formData = new NVPair[5];

            formData[0] = new NVPair( "password", m_password );
            formData[1] = new NVPair( "p_test_cookies", "Y" );
            formData[2] = new NVPair( "ssousername", m_username );
            formData[3] = new NVPair( "site2pstoretoken", parser.getToken() );

            rsp = conn2.Post( "/ifs/files/ifs/webui/jsps/login.jsp", formData );
            
            readData(rsp, 0);
            /*parser.parse( new InputStreamReader( rsp.getInputStream() ) );
            System.out.println("parser.getToken() = " + parser.getToken());
             NVPair[] formData1 = new NVPair[5];

            formData1[0] = new NVPair( "password", m_password );
            formData1[1] = new NVPair( "v", "v1.4" );
            formData1[2] = new NVPair( "ssousername", m_username );
            formData1[3] = new NVPair( "site2pstoretoken", "v1.4~E5E175CD~6F505445F2DDA6038184C0BD59771B616EC124A1204D1DA9FF6C86C2C76F2C43AF3A9A8AC97EE21542CB6A33062C076A0773A3A635A6CA8A4D283476CF5A32E5B54CC2BF01D8890071AE0563B38AF1D32ACE67BE1E82AECEF9DE2D1096119198AABF0CA743A248DBEC6D365ECCBF9CD150F7FD10368B3162D2FC373D1DC3E4645025D098211237EC104DFAACEAC0B3FBEE04CD8B63A910305BFDDA110FEE0EAACC87D647313BFEFCD4A3DCB2D3A30B185FFE4DB5820D28B386B82C60756DCE8F4CA710C5571C1962927C73034E553C0BFD9311392FC7438945790C5D0A3CA7F3" );
            formData1[4] = new NVPair( "locale", "en-US" );*/

            /*HTTPConnection conn2 = null;

            conn2 = new HTTPConnection( PROTOCOL_SCHEME_HTTPS, "ifs.statschippac.com", DEFAULT_SSL_PORT );
            CookieModule.setCookiePolicyHandler( null );
            conn2.addDefaultModule( CookieModule.class, -1 );*/
           /* rsp = conn2.Get("/ifs/files/ifs/webui/jsps/login.jsp?userName=ikns_becky&passWord=st853515&step=try&action=Login");
            readData(rsp, 0);*/
            /*rsp = conn2.Get("/ifs/files/ifs/webui/jsps/viewer.jsp?noCache=1215778331453");
            readData(rsp, 0);
            rsp = conn2.Get( "/ifs/files/ifs/webui/jsps/container.jsp?path=/home/customer/IKANOS/ikns_becky/IKANOS/IKANOS/ARCHIVE/DAILY" );
                              System.out.println(" getEffectiveURI= " + rsp.getEffectiveURI() );
            System.out.println(" getEffectiveURI= " + rsp.getOriginalURI() );*/
            //readData( rsp,0 );

             /*HTTPConnection conn3 = null;

            conn3 = new HTTPConnection( PROTOCOL_SCHEME_HTTPS, "files.statschippac.com", DEFAULT_SSL_PORT );
            CookieModule.setCookiePolicyHandler( null );
            conn3.addDefaultModule( CookieModule.class, -1 );*/

            //rsp = conn3.Get( "/content/app/alternateExplorerPage.jspx?_afPfm=5");

           /* readData( rsp,0 );*/

            //rsp = conn.Get( "/discoverer/viewer?us=ikns_becky&pw=st853515&db=odsprod&wb=ODSU3RPT.003.0%20Dropship%20Inventory%20Report%20Query&nlsl=en-us" );

            //rsp = conn.Get( "/discoverer/viewer?&cn=tm4i_connection1&us=%7E27IKNS_BECKY%7E27&db=odsprod&lm=discoverer&eul=ODS_EUL&nlsl=en-us&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227");

            //rsp = conn.Get("/discoverer/viewer?_lfs=true&cn=tm4i_connection1&pw=st853515&db=odsprod&eul=ODS_EUL&formSubmitted.x=27&formSubmitted.y=13&lm=discoverer&nlsl=en-us&pg=1&us=IKNS_BECKY&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227");


            //rsp = conn.Get( "/discoverer/viewer?&cn=tm4i_connection1&us=%7E27IKNS_BECKY%7E27&db=odsprod&lm=discoverer&eul=ODS_EUL&nlsl=en-us&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227&pg=1&_act=seo");

            //
            //rsp = conn.Post( "/discoverer/viewer?&cn=tm4i_connection1&us=~27IKNS_BECKY~27&db=odsprod&lm=discoverer&eul=ODS_EUL&nlsl=en-us&wbk=0060_WIP_AND_INVENTORY_SEARCH_QUERY2014&wsk=10227&pg=1&wqcn=true&fm=xls");

            //rsp = conn.Get("/discoverer/viewer?&_lfs=true&cn=tm4i_connection1&pw=st853515&db=odsprod&eul=ODS_EUL&fm=csv&lm=discoverer&nlsl=en-us&pg=1&qp_Plant1=SCM~2cSCC~2cSCK~2cSCS&us=~27IKNS_BECKY~27&wbk=0030_DROPSHIP_INVENTORY_REPORT_QUERY311&wsk=6528&wqcn=true");

            //readData( rsp1,0 );

            /*if ( rsp != null )
            {
                reader = new BufferedReader( new InputStreamReader( rsp.getInputStream() ) );
                if ( reader != null )
                {
                    System.out.println( "\tDownloading and saving the Wip Inventory Report for all Plants..." );
                    log( "\tDownloading and saving the Wip Inventory Report for all Plants..." );
                    AdaptorUtils.saveAsFile( reader , m_dataOutputDir, FILE_NAME_SHIP_STATUS + "-" + DateUtil.getFormattedTimeStamp() , AdaptorUtils.FILE_EXTN_CSV);
                }
                else
                {
                    log( "Could not save Wip Inventory Report for all Plants from Buffer Reader" );
                    throw new ScalarException( "Could not save Wip Inventory Report for all Plants from Buffer Reader" );
                }
            }
            else
            {
                log( "Could not create response object of Wip Inventory Report for all Plants" );
                throw new ScalarException( "Could not create response object of Wip Inventory Report for all Plants" );
            }*/
        }
        finally
        {
             if ( reader != null )
             {
                 reader.close();
             }
        }
    }

    public void readData( HTTPResponse rsp, int debug ) throws Exception
    {
        byte[] data = new byte[4096];
        if ( debug == 0 )
        {
            while ( rsp.getInputStream().read( data ) != -1 )
            {
                //System.out.println( new String( data ) );
                log( new String( data ) );
            }
        }
    }

    private void log( String message )
    {

        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }
}

